use base64::{engine::general_purpose, Engine as _};
use dioxus::prelude::*;
use openssl::pkey::Private;
use openssl::rsa::{Padding, Rsa};

use crate::components::copy::Copy;

#[derive(PartialEq, Clone)]
enum CryptoMode {
    Aes,
    Rsa,
}

#[component]
pub fn CryptoSuite() -> Element {
    let mut crypto_mode = use_signal(|| CryptoMode::Aes);

    rsx! {
        div { class: "flex-1 flex flex-col",
            div { class: "flex-1 p-8 overflow-auto",
                div { class: "max-w-4xl mx-auto space-y-6",
                    // 模式切换标签
                    div { class: "flex border-b border-gray-200",

                        button {
                            class: format!("px-4 py-2 font-medium text-sm border-b-2 {}",if *crypto_mode.read() == CryptoMode::Rsa {
                                "border-blue-500 text-blue-600"
                            } else {
                                "border-blue-500 text-blue-600"
                            }),
                            onclick: move |_| crypto_mode.set(CryptoMode::Rsa),
                            "RSA 加解密"
                        }
                    }

                    // 动态显示对应组件
                     RsaEncryptor {} ,

                }
            }
        }
    }
}

#[component]
fn RsaEncryptor() -> Element {
    let mut input_text = use_signal(|| String::new());
    let mut public_key = use_signal(|| String::new());
    let mut private_key = use_signal(|| String::new());
    let mut key_size = use_signal(|| 2048);
    let mut output_text = use_signal(|| String::new());
    let mut is_encrypt = use_signal(|| true);
    let mut copy_status = use_signal(|| String::new());
    let mut key_status = use_signal(|| "未生成".to_string());

    // 生成RSA密钥对
    let generate_keys = move |_| match Rsa::generate(*key_size.read() as u32) {
        Ok(rsa) => {
            let pub_key = rsa.public_key_to_pem().unwrap();
            let priv_key = rsa.private_key_to_pem().unwrap();
            public_key.set(String::from_utf8(pub_key).unwrap());
            private_key.set(String::from_utf8(priv_key).unwrap());
            key_status.set("已生成".to_string());
        }
        Err(e) => {
            key_status.set(format!("生成失败: {}", e));
        }
    };

    // 执行加密/解密
    let perform_crypto = move |_| {
        let result = if *is_encrypt.read() {
            rsa_encrypt(&input_text.read(), &public_key.read())
        } else {
            rsa_decrypt(&input_text.read(), &private_key.read())
        };

        output_text.set(result.unwrap_or_else(|e| format!("Error: {}", e)));
    };

    rsx! {
        div { class: "space-y-6",
            // 标题和描述
            div { class: "space-y-2",
                h1 { class: "text-2xl font-bold text-gray-900", "RSA 加解密工具" }
                p { class: "text-gray-600", "支持 RSA 密钥生成、加密和解密" }
            }

            // 密钥生成卡片
            div { class: "bg-white border border-gray-200 rounded-xl shadow-sm",
                div { class: "p-6",
                    div { class: "grid grid-cols-1 md:grid-cols-3 gap-4",
                        // 密钥长度选择
                        div { class: "space-y-2",
                            label { class: "block text-sm font-medium text-gray-700", "密钥长度" }
                            select {
                                onchange: move |e| {
                                    if let Ok(size) = e.value().parse::<usize>() {
                                        key_size.set(size);
                                    }
                                },
                                value: "{key_size}",
                                class: " w-full
                                px-4 py-2
                                text-sm text-gray-800
                                bg-white
                                border border-gray-300
                                rounded-lg
                                shadow-sm
                                transition-all
                                focus:outline-none
                                focus:ring-2 focus:ring-blue-500
                                focus:border-blue-500
                                hover:border-gray-400
                                cursor-pointer
                                appearance-none",
                                option { value: "1024", "1024位 (不推荐)" }
                                option { value: "2048", "2048位 (推荐)" }
                                option { value: "4096", "4096位 (更安全)" }
                            }
                        }

                        // 生成按钮
                        div { class: "flex items-end",
                            button {
                                onclick: generate_keys,
                                class: "w-full px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500",
                                "生成密钥对"
                            }
                        }

                        // 生成状态
                        div { class: "flex items-center",
                            span {
                                class: format!("text-sm {}",if key_status.read().contains("失败") { "text-red-500" } else { "text-gray-500" }),
                                "{key_status}"
                            }
                        }
                    }

                    // 密钥显示区域
                    div { class: "mt-4 space-y-4",
                        div { class: "space-y-2",
                            label { class: "block text-sm font-medium text-gray-700", "公钥" }
                            textarea {
                                value: "{public_key}",
                                oninput: move |e| public_key.set(e.value()),
                                class: "w-full h-24 px-3 py-2 border border-gray-300 rounded-lg font-mono text-sm focus:ring-blue-500 focus:border-blue-500",
                                placeholder: "-----BEGIN PUBLIC KEY-----"
                            }
                        }

                        div { class: "space-y-2",
                            label { class: "block text-sm font-medium text-gray-700", "私钥" }
                            textarea {
                                value: "{private_key}",
                                oninput: move |e| private_key.set(e.value()),
                                class: "w-full h-24 px-3 py-2 border border-gray-300 rounded-lg font-mono text-sm focus:ring-blue-500 focus:border-blue-500",
                                placeholder: "-----BEGIN PRIVATE KEY-----"
                            }
                        }
                    }
                }
            }

            // 加解密卡片
            div { class: "bg-white border border-gray-200 rounded-xl shadow-sm",
                div { class: "p-6",
                    div { class: "space-y-4",
                        // 输入文本区域
                        div { class: "space-y-2",
                            label { class: "block text-sm font-medium text-gray-700",
                                if *is_encrypt.read() { "明文" } else { "密文 (Base64)" }
                            }
                            textarea {
                                oninput: move |e| input_text.set(e.value()),
                                value: "{input_text}",
                                class: "w-full h-40 px-3 py-2 border border-gray-300 rounded-lg font-mono text-sm focus:ring-blue-500 focus:border-blue-500",
                                placeholder: if *is_encrypt.read() {
                                    "输入要加密的文本"
                                } else {
                                    "输入要解密的Base64密文"
                                }
                            }
                        }

                        // 操作区
                        div { class: "grid grid-cols-1 md:grid-cols-3 gap-4",
                            // 加密/解密切换
                            div { class: "space-y-2",
                                label { class: "block text-sm font-medium text-gray-700", "操作类型" }
                                select {
                                    onchange: move |e| is_encrypt.set(e.value() == "encrypt"),
                                    value: if *is_encrypt.read() { "encrypt" } else { "decrypt" },
                                    class: " w-full
                                    px-4 py-2
                                    text-sm text-gray-800
                                    bg-white
                                    border border-gray-300
                                    rounded-lg
                                    shadow-sm
                                    transition-all
                                    focus:outline-none
                                    focus:ring-2 focus:ring-blue-500
                                    focus:border-blue-500
                                    hover:border-gray-400
                                    cursor-pointer
                                    appearance-none",
                                    option { value: "encrypt", "加密" }
                                    option { value: "decrypt", "解密" }
                                }
                            }

                            // 执行按钮
                            div { class: "flex items-end col-span-2",
                                button {
                                    onclick: perform_crypto,
                                    class: "w-full px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500",
                                    if *is_encrypt.read() { "加密" } else { "解密" }
                                }
                            }
                        }
                    }
                }
            }

            // 结果卡片
            if !output_text.read().is_empty() {
                div { class: "bg-white border border-gray-200 rounded-xl shadow-sm",
                    div { class: "p-6",
                        div { class: "flex justify-between items-center mb-4",
                            h2 { class: "text-lg font-semibold text-gray-900",
                                if *is_encrypt.read() { "加密结果 (Base64)" } else { "解密结果" }
                            }
                            Copy{
                                val:output_text.clone()
                            }
                        }
                        div { class: "p-4 bg-gray-50 rounded-lg font-mono text-sm whitespace-pre-wrap overflow-x-auto",
                            "{output_text}"
                        }

                    }
                }
            }
        }
    }
}

// RSA加密函数
fn rsa_encrypt(plaintext: &str, public_key: &str) -> Result<String, String> {
    let rsa = Rsa::public_key_from_pem(public_key.as_bytes())
        .map_err(|e| format!("公钥解析失败: {}", e))?;

    let mut buf = vec![0; rsa.size() as usize];
    let len = rsa
        .public_encrypt(plaintext.as_bytes(), &mut buf, Padding::PKCS1)
        .map_err(|e| format!("加密失败: {}", e))?;

    Ok(general_purpose::STANDARD.encode(&buf[..len]))
}

// RSA解密函数
fn rsa_decrypt(ciphertext: &str, private_key: &str) -> Result<String, String> {
    let ciphertext = general_purpose::STANDARD
        .decode(ciphertext)
        .map_err(|e| format!("Base64解码失败: {}", e))?;

    let rsa = Rsa::private_key_from_pem(private_key.as_bytes())
        .map_err(|e| format!("私钥解析失败: {}", e))?;

    let mut buf = vec![0; rsa.size() as usize];
    let len = rsa
        .private_decrypt(&ciphertext, &mut buf, Padding::PKCS1)
        .map_err(|e| format!("解密失败: {}", e))?;

    String::from_utf8(buf[..len].to_vec()).map_err(|e| format!("UTF-8解码失败: {}", e))
}
